const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const {FAVICON_PATH, TEMPLATE_PATH} = require('../config');

const join = (filePath) => path.join(__dirname, '..', filePath);

console.log('开发模式：', process.env.NODE_ENV);

module.exports = {
  output: {
    path: join('dist'),
    filename: 'js/[name].[hash:7].js',
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: { loader: 'babel-loader' },
      },
      {
        test: /.html$/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: false },
          },
        ],
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader?javascriptEnabled'],
      },
      {
        test: /\.(ico|png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
        exclude: /favicon\.png$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10000,
            name: 'images/[name].[hash:7].[ext]',
          },
        }],
      },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      filename: 'index.html',
      template: TEMPLATE_PATH,
      inject: 'body',
      favicon: FAVICON_PATH,
      hash: true,
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[hash:7].css',
      chunkFilename: 'css/[id].[hash:7].css',
    }),
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(process.env),
    }),
  ],
  resolve: {
    extensions: ['.js', '.less', '.css'],
    alias: {
      src: join('src'),
    },
    modules: [
      'node_modules',
      join('src'),
    ],
  },
  optimization: {
    namedChunks: true,
    splitChunks: {
      minSize: 30000,
      cacheGroups: {
        commons: {
          chunks: 'initial', // "initial", "async", "all"
          name: 'commons',
          minChunks: 2,
          maxInitialRequests: 5,
          minSize: 0,
        },
        vendor: {
          chunks: 'initial', // "initial", "async", "all"
          test: /node_modules/,
          name: 'vendor',
          priority: -10,
          enforce: true,
        },
      },
    },
    // runtimeChunk: {
    //   name: 'runtime',
    // },
  },
};